<!--新增任务管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-suffix="：">
        <div class="detail_title">
          基础信息
          <el-button v-if="form.evaluateQuestStatus" :type="form.evaluateQuestStatus == '暂存' ? 'primary' : 'danger'" plain size="mini" class="top_btn"
            @click="topBtn">{{form.evaluateQuestStatus == '暂存'? "执行评估任务" : "暂停评估任务"}}</el-button>
        </div>
        <el-row class="detail_card">
          <el-row>
            <el-col :span="24">
              <el-form-item label="评估任务名称" prop="evaluateQuestTitle">
                <el-input v-model="form.evaluateQuestTitle" placeholder="请输入评估任务名称" maxlength="20" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="业务分类" prop="evaluateQuestBusiness">
                <el-select v-model="form.evaluateQuestBusiness" placeholder="请选择业务分类" filterable clearable>
                  <el-option v-for="item in businessList" :key="item.dictCode" :label="item.dictValue" :value="item.dictValue">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联核心政策" prop="evaluateQuestCorePolicy">
                <el-select v-model="form.evaluateQuestCorePolicy" placeholder="请选择核心政策" filterable clearable>
                  <el-option v-for="(item,index) in coreList" :key="index" :label="item" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="评估任务描述" prop="evaluateQuestContent">
                <el-input type="textarea" v-model="form.evaluateQuestContent" placeholder="请输入评估任务描述" maxlength="20" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
        <div class="detail_title mt20">评估结果模板</div>
        <div class="detail_card">
          <el-row>
            <el-col :span="24">
              <el-form-item label="评估模板">
                <el-upload action="" :show-file-list="false"  ref="upload" multiple auto-upload :http-request="uploadFile"  class="upload-demo">
                  <el-button size="small" type="primary">上传模板</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="form.zhpgEvaluateTemplateList && form.zhpgEvaluateTemplateList.length > 0">
            <div v-for="(item,index) in form.zhpgEvaluateTemplateList" :key="index">
              <div class="flex">
                <p style="width: 450px">{{item.evaluateTemplateTitle}}</p>
                <div>
                  <el-button @click="handleFile('del',item)"  type="primary" plain icon="el-icon-delete" size="mini">删除</el-button>
                  <el-button @click="handleFile('download',item)"  v-if="params.type !== 'add'" type="primary" plain icon="el-icon-download" size="mini">下载</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="detail_title mt20">评估专家、评估规则</div>
        <div class="detail_card">
          <el-row>
            <el-col :span="24">
              <el-form-item label="评估专家" prop="evaluateExpertIds">
                <span @click="xxBtn" class="xx">详细</span>
                <el-checkbox-group @change="onExpert" v-model="form.evaluateExpertIds" size="small">
                  <el-checkbox :label="item.userId"  border v-for="item in expertList" :key="item.userId">
                    {{item.nickName}}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="评估周期" prop="evaluateQuestCycle">
                <el-radio-group v-model="form.evaluateQuestCycle">
                  <el-radio :label="item.dictValue" v-for="(item,index) in cycleList" :key="index">{{item.dictValue}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="display: flex;padding-top: 15px">
            <div>
              <el-form-item label="评估触发时间" prop="evaluateQuestTriggerMonth">
                <div class="monthP">
                  <span class="fl">每月</span>
                  <el-select v-model="form.evaluateQuestTriggerMonth">
                    <el-option v-for="item in monthDate" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                  <span class="fl hao">号</span>
                </div>
              </el-form-item>
            </div>
            <div>
              <el-form-item prop="evaluateQuestTriggerHours" label-width="0px">
                <div class="monthP">
                  <el-time-select
                    v-model="form.evaluateQuestTriggerHours"
                    :picker-options="{
                    start: '08:00',
                    step: '00:15',
                    end: '23:30'
                    }"
                    placeholder="选择时间">
                  </el-time-select>
                  <span class="fl hao auto">自动触发</span>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div class="detail_title mt20">评估指标</div>
      <p @click="drBtn" class="zb_add">指标导入</p>
      <el-table v-loading="loading" :data="form.zhpgEvaluateIndexList" border>
        <el-table-column label="序号" width="50" align="center" type="index" />
        <el-table-column label="字段名" align="center"  prop="evaluateIndexZdmc" />
        <el-table-column label="字段值" align="center"  prop="evaluateIndexZdz" />
        <el-table-column label="评估指标名称（字段描述）" align="center"  prop="evaluateIndexName">
        </el-table-column>
        <el-table-column label="是否专家评分" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.evaluateIndexIszj">
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" @click="handleTable('del',scope.row,form.zhpgEvaluateIndexList,scope.$index)">删除</el-button>
            <el-button size="small" :disabled="scope.$index === 0" @click="handleTable('prev',scope.row,form.zhpgEvaluateIndexList,scope.$index)">上移</el-button>
            <el-button size="small" :disabled="scope.$index === form.zhpgEvaluateIndexList.length - 1" @click="handleTable('next',scope.row,form.zhpgEvaluateIndexList,scope.$index)">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 50px;display: flex;align-items: center;justify-content: center;">
        <el-pagination background layout="prev, pager, next" :total="total"
                       @current-change="onPageChange"></el-pagination>
      </div>
      <div  class="end-btns">
        <span class="flex flex-content-start">
          <el-button type="danger" @click="del" v-if="this.params.type === 'detail'">删除评估任务</el-button>
        </span>
        <span class="flex flex-content-end">
          <el-button type="primary" plain>取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </span>
      </div>
    </el-row>
    <!-- 执行任务 -->
    <el-dialog :title="form.evaluateQuestStatus === '暂存' ? '开始评估任务' :'暂停评估任务'" :visible.sync="zxShow" width="500px" append-to-body>
      <p>确定将{{form.evaluateQuestStatus === '暂存' ? '开始' :'暂停'}}评估任务：<span>{{form.evaluateQuestTitle}}</span></p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="zxOk">确 定</el-button>
        <el-button @click="zxShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 专家 -->
    <el-dialog title="考核专家详细" :visible.sync="xxShow" width="700px" append-to-body>
      <div class="xx_item" v-for="(item,index) in expertList" :key="index">
        <div class="xx_name">
          <svg-icon icon-class="peoples" class="mr20" />{{item.nickName}}（用户名）
        </div>
        <div class="xx_content">
          <div class="xx_content_item">用户名：{{item.nickName}}</div>
          <div class="xx_content_item">手机号：{{item.phonenumber}}</div>
          <div class="xx_content_item">邮箱：{{item.email}}</div>
        </div>
        <div class="xx_bz" v-if="item.remark">备注：{{item.remark}}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="xxShow = false">确 定</el-button>
        <el-button @click="xxShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog title="指标导入" :visible.sync="drShow" width="500px" append-to-body>
      <el-tree :data="drData" accordion :default-checked-keys="form.evaluateIndexIds" @check="checkChange" :expand-on-click-node="false" check-strictly @check-change="handleCheckChange" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current
        :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handeleExport">导入</el-button>
        <el-button @click="drShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryBusiness,
  corePolicies,
  queryExpertList,
  uploadFileInter,
  downLoadInter,
  delFile,
  queryCycle,
  addTask,
  taskDetail,
  startQuest,
  stopQuest,
  delQuestion, deleteQuest, getTree, upDateTask
} from '@/api/eval'
  import {openMessage,monthDate,deepClone} from '@/utils'
  export default {
    name: "User",
    dicts: ["sys_normal_disable", "sys_user_sex","evaluate_index_iszj"],
    mounted() {
      this.uploadUrl = process.env.VUE_APP_BASE_API
      this.params = this.$route.query
      console.log(this.params.id)
      if (this.params.id) {
        taskDetail(this.params.id).then((res) => {
          this.form = res.data
        })
      }else {
        delete this.form.id
      }
    },
    data() {
      return {
        params:{},//参数
        title: "执行评估任务",
        fileList: [],
        total: 0,
        files:[],
        uploadUrl:'',
        expertList:[],//专家列表
        businessList:[],//业务分类
        coreList:[],
        //数据
        userList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        cycleList:[],//周期
        loading:false,
        form: {
          zhpgEvaluateExpertList: [],//评估专家集合
          evaluateQuestCycle: '',//评估任务周期
          evaluateQuestTitle:'',//评估任务名称
          evaluateQuestCorePolicy:'',//关联核心政策
          evaluateQuestStatus:'',//
          evaluateQuestContent:'',//评估任务描述
          evaluateQuestBusiness:'',//业务分类
          zhpgEvaluateTemplateList:[],//评估模版集合
          zhpgEvaluateIndexList:[],//评估指标集合
          evaluateQuestTriggerMonth:'',//评估任务触发时间每月{}号
          evaluateQuestTriggerHours:'',//	评估任务触发时间{}时分
          evaluateExpertIds:[], //专家复选框
          evaluateIndexIds:[],//树勾选的id
        },
        rules: {
          evaluateQuestTitle:[{required:true,message:'请输入评估任务名称',trigger:'blur'}],
          evaluateQuestBusiness:[{required:true,message:'请选择业务分类',trigger:'blur'}],
          evaluateQuestCorePolicy:[{required:true,message:'请选择关联核心政策',trigger:'blur'}],
          evaluateQuestContent:[{required:true,message:'请输入评估任务描述',trigger:'blur'}],
          evaluateQuestCycle:[{required:true,message:'请选择评估周期',trigger:'blur'}],
          evaluateExpertIds:[{required:true,message:'请选择评估专家',trigger:'blur'}],
          evaluateQuestTriggerMonth:[{required:true,message:'请选择几号',trigger:'blur'}],
          evaluateQuestTriggerHours:[{required:true,message:'请选择时间',trigger:'blur'}],
        },
        monthDate,
        drData: [],
        defaultProps: {
          children: "children",
          label: "label",
        },
        zxShow: false,
        zxStatus: 0,
        xxShow: false,
        drShow: false,
        treeSelect:[],
      };
    },
    watch: {},
    created() {
      queryBusiness().then(({code,data}) => {
        this.businessList = data
      })
      queryExpertList().then(({code,data}) => {
        this.expertList = data
      })
      queryCycle().then(({code,data}) => {
        this.cycleList = data
      })
      corePolicies().then(({code,data}) => {
        this.coreList = data
      })
      getTree().then((res) => {
        this.drData = res.data
      })
    },
    methods: {
      //指标导入
      drBtn() {
        this.drShow = true;
      },
      //专家详细
      xxBtn() {
        this.xxShow = true;
      },
      onPageChange(e) {
        // this.form.pageNum = e
        // this.queryPressurePages()
      },
      handeleExport() {
        this.form.zhpgEvaluateIndexList = []
        this.treeSelect.forEach((item,index) => {
          if (!item.children) { //最小的叶子节点
            let obj = {
              evaluateIndexName:item.evaluateIndexName,//评估指标名称
              evaluateIndexZdmc:item.evaluateIndexZdmc,//字段名称
              evaluateIndexZdz:item.evaluateIndexZdz,//字段值
              evaluateIndexId:item.id,
              evaluateIndexSort:index + 1,
              evaluateIndexIszj:'否'
            }
            this.form.zhpgEvaluateIndexList.push(obj)
          }
        })
        let temList = deepClone(this.form.zhpgEvaluateIndexList)
        this.form.evaluateIndexIds = temList.map(item => item.evaluateIndexId)
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.form.evaluateIndexIds);
        })
        this.drShow = false
      },
      // 指标导入的删除事件
      handleTable(type,item,list,index) {
        const data = deepClone(list)
          switch (type) {
            case 'del': //删除
              this.$confirm('您确定要删除吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.form.zhpgEvaluateIndexList.splice(index,1)
                let tempList = deepClone(this.form.zhpgEvaluateIndexList)
                this.form.evaluateIndexIds = tempList.map(item => item.evaluateIndexId)
                this.$nextTick(() => {
                  this.$refs.tree.setCheckedKeys(this.form.evaluateIndexIds);
                })
                openMessage('删除成功','success')
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }).catch(() => {
                openMessage('已取消删除','info')
              });
              break;
            case 'prev'://上移
              if (index != 0) {
                // 上移第一项无需上移
                data.splice(index - 1, 2, list[index], list[index - 1]);
              } else {
                console.log('已经是首项了');
              }
              this.form.zhpgEvaluateIndexList = data
              break;
            case 'next'://下移
              // 下移最后一项无需下移
              if (index != list.length) {
                data.splice(index, 2, list[index + 1], list[index]);
              } else {
                console.log('已经是最后一项了');
              }
              this.form.zhpgEvaluateIndexList = data
              break;
          }
      },
      checkChange(data,obj) {
        this.treeSelect = []
        this.treeSelect = obj.checkedNodes
      },
      handleCheckChange(data, checked, indeterminate) {
        // console.log(data, checked, indeterminate)
      },
      //执行任务
      topBtn() {
        this.zxShow = true;
      },
      // 删除评估任务
      del() {
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteQuest(this.form.id).then((res) => {
            openMessage('删除成功','success')
            setTimeout(() => {
              this.$router.back()
            },1500)
          })
        }).catch(() => {
          openMessage('已取消删除','info')
        });
      },
      zxOk() {
        if (this.form.evaluateQuestStatus && this.form.evaluateQuestStatus === '暂存') {
          startQuest(this.form.id).then(res => {
            openMessage('已开启执行任务','success')
          })
        }else {
          stopQuest(this.form.id).then(res => {
            openMessage('已暂停执行任务','error')
          })
        }
        this.zxShow = false
      },
      saveData() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.form.zhpgEvaluateExpertList = []
            this.form.evaluateExpertIds.forEach((item,index) => {
              this.expertList.forEach((val,key) => {
                if (item === val.userId) {
                  let obj = {
                    evaluateExpertUserName:val.nickName,
                    evaluateExpertUserId:val.userId
                  }
                  this.form.zhpgEvaluateExpertList.push(obj)
                }
              })
            })
            if (this.params.type === 'add') {
              addTask(this.form).then((res) => {
                openMessage('新增成功','success')
                this.$refs.form.resetFields()
                startQuest(res.data.id).then(respone => {
                })
              }).catch(err => {
                openMessage('新增失败','info')
              })
            }else {
              upDateTask(this.form).then((res) => {
                openMessage('保存成功','success')
                this.$refs.form.resetFields()
              }).catch(err => {
                openMessage('保存失败','info')
              })
            }
            setTimeout(() => {
              this.$router.back()
            },1500)
          }
        })
      },
      onExpert(e) {
        this.form.evaluateExpertIds = e
      },
      uploadFile(raw) {
        let fd = new FormData()
        fd.append('evaluateQuestId',0)
        fd.append('file',raw.file)
        uploadFileInter(fd).then(({data}) => {
          let obj = {
            evaluateTemplateTitle:data.evaluateTemplateTitle,
            id:data.id
          }
          this.form.zhpgEvaluateTemplateList.push(obj)
          openMessage('上传成功','success')
          this.$refs.upload.clearFiles()
        })
      },
      handleFile(type,item,index) {
        switch (type) {
          case 'del' :
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              delFile(item.id).then(({code,data}) => {
                if (code === 200) {
                  this.form.zhpgEvaluateTemplateList.splice(index,1)
                  openMessage('删除成功','success')
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
            break;
          case 'download':
            downLoadInter(item.id).then(result => {
              //创建一个Blob对象接收后端传来的文件流
              const blob = new Blob([result], {
                type: 'application/octet-stream'
              })
              const downloadElement = document.createElement('a')
              // 创建下载的链接
              const href = window.URL.createObjectURL(blob)
              downloadElement.href = href
              // 下载后文件名
              downloadElement.download = item.evaluateTemplateTitle
              document.body.appendChild(downloadElement)
              // 点击下载
              downloadElement.click()
              // 下载完成移除元素
              document.body.removeChild(downloadElement)
              // 释放掉blob对象
              window.URL.revokeObjectURL(href)
            })
            break;
        }
      },
      download() {
        downLoadInter()
      },
    },
  };
</script>
<style lang="scss">
.el-tree-node{
  .is-leaf + .el-checkbox .el-checkbox__inner{
    display: inline-block;
  }
  .el-checkbox .el-checkbox__inner{
    display: none;
  }
}
</style>
<style lang="scss" scoped>
  .end-btns{
    padding-top: 20px;
  }
  .xx_content {
    background: #efefef;
    display: flex;
    height: 50px;
    align-items: center;
    justify-content: space-around;
  }

  .xx_bz {
    text-align: center;
    height: 50px;
    background: #efefef;
    line-height: 50px;
    margin-bottom: 20px;
  }

  ::v-deep .el-dialog__header {
    background-color: #354161;
    padding-bottom: 20px;
  }

  ::v-deep .el-dialog__footer {
    background-color: #f1f2f4;
    padding-top: 20px;
  }

  ::v-deep .el-dialog__title {
    color: white;
  }

  .detail_title {
    height: 25px;
    display: flex;
    align-items: center;
    font-size: 17px;
    color: rgb(17, 120, 204);
    font-weight: bolder;
    padding-left: 15px;
    border-left: 4px solid rgb(17, 120, 204);
    margin-bottom: 15px;
    position: relative;
  }

  .detail_title .top_btn {
    position: absolute;
    right: 20px;
  }

  .detail_card {
    box-shadow: 0 0px 10px rgba(0, 0, 0, 0.12), 0 2px 5px rgba(0, 0, 0, 0.08);
    box-sizing: border-box;
    padding: 20px;
    padding-right: 30px;
    border-radius: 5px;
    min-height: 80px;
  }

  .detail_card .el-row .el-form-item {
    margin: 10px;
  }

  ::v-deep .el-select.el-select--medium {
    width: 100%;
  }

  .zb_add {
    width: 100px;
    color: rgb(17, 120, 204);
    font-size: 13px;
    cursor: pointer;
  }

  ::v-deep .el-radio-group {
    display: flex;
    flex-wrap: wrap;
  }

  ::v-deep .el-radio-group label {
    margin-top: 10px;
    width: 40%;
  }

  .monthP {
    display: flex;
    align-items: center;
    margin-top: 0px;
  }
  .fl{
    display: inline-block;
    width: 64px;
    &.hao{
      margin-left: 15px;
    }
  }
  .monthP .el-col {
    margin: 0 10px;
  }

  .xx {
    color: rgb(17, 120, 204);
    cursor: pointer;
  }
</style>
